package com.antilia.infomaresme.data.dao.hibernate;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import com.antilia.infomaresme.data.dao.interfaces.IUserMessagesDao;
import com.antilia.infomaresme.data.dataobjects.User;
import com.antilia.infomaresme.data.dataobjects.UserMessage;
/**
 * @author Ernesto
 *
 */
public class UserMessagesDaoHibernateImp extends AbstractDaoHibernateImpl<UserMessage> implements IUserMessagesDao{

	public UserMessagesDaoHibernateImp()
	{
		super(UserMessage.class);
	}
	
	
	@SuppressWarnings("unchecked")
	public List<UserMessage> getItems(User user, int start, int size, boolean dateAscending) {
		Criteria criteria = getSession().get().createCriteria(UserMessage.class);
		criteria.setFetchSize(size);
		criteria.setFirstResult(start);
		configureCriteria(criteria, user);		
		if(dateAscending)
			criteria.addOrder(Order.asc("date"));
		else 
			criteria.addOrder(Order.desc("date"));
		return (List<UserMessage>)criteria.list();
	}
	 
	public Long countItems(User user) {
		Criteria criteria = session.get().createCriteria(UserMessage.class);
		criteria.setProjection(Projections.rowCount());
		configureCriteria(criteria, user);
		return (Long)(criteria.uniqueResult());
	}
	
	private void configureCriteria(Criteria criteria, User user) {
		if(user != null) {
			criteria.add(Restrictions.eq("user", user));
		}
	}
}
